let room = 1
let session = []
/**
 * {
 *  id: [1, 2],
 *  room: 1
 * }
 */

module.exports = {
  join(id, to, socket) {
    let flag = false
    for (let el of session) {
      if (el.id.includes(id) && el.id.includes(to)) {
        socket.join(el.room)
        return
      }else if((el.id.includes(id) || el.id.includes(to)) && el.id.length === 1) {
        el.id.push(el.id[0] == id ? to : id)
        socket.join(el.room)
        flag = true
      }
    }
    if(!flag) {
      let param = [id, to]
      if(to === undefined)
        param = [id]
      session.push({ id: param, room: room})
      socket.join(room)
      room++
    }
  },
  leave(id) {
    let flag = false
    for (let index = 0; index < session.length; index++) {
      let el = session[index]
      if (el.id.includes(id)) {
        if (el.id.length == 1)
          session.splice(index, 1)
        else
          el.id = [parseInt(el.id[0]) + parseInt(el.id[1]) - id + '']
      }
    }
  },
  room(id, to) {
    let rtn = false
    session.forEach(el => {
      if (!rtn && el.id.includes(id) && el.id.includes(to)) {
        rtn = el
      }
    })
    return rtn ? rtn.room : false
  }
}